package com.guiji.text2video.fastvideo.utils;

import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

/**
 * Copyright (C), 2018-2021
 * FileName: PriorityRunnable
 * Author:   scl
 * Date:     2021/7/16 13:54
 * Description: 带优先级的线程类
 */

public class PriorityRunnable implements Runnable, Comparable<PriorityRunnable> {
    private final static AtomicLong seq = new AtomicLong();
    private final long seqNum;
    private Runnable run;

    private int priority;

    public PriorityRunnable(Runnable run, int priority) {
        seqNum = seq.getAndIncrement();
        this.run = run;
        this.priority = priority;
    }

    @Override
    public void run() {

        this.run.run();
    }

    @Override
    public int compareTo(PriorityRunnable other) {
        int res = 0;
        if (this.priority == other.priority) {
            if (other.run != this.run) {
                // ASC
                res = (seqNum < other.seqNum ? -1 : 1);
            }
        } else {
            // DESC
            res = this.priority > other.priority ? -1 : 1;
        }
        return res;
    }
}